import axios from "axios";
import { showLoadingToast } from 'vant';
import { paths } from '@/utils/paths';

const baseUrl = paths.api
let loading;

const instance = axios.create({
    baseURL: baseUrl,
    timeout: 60000,
    headers: {
      // 解决跨域问题
      'Content-Type': 'application/x-www-form-urlencoded'
      // 'Content-Type': 'multipart/form-data'
    }
  });

   // 请求拦截器
   instance.interceptors.request.use(config => {
    //这里loading
    loading = showLoadingToast({
      duration:0,
      message: '加载中...',
      forbidClick: true,
    });
    return config
  }, error => {
    return Promise.reject(error)
  });

  instance.interceptors.response.use(config => {
    // let code = config.data.errcode;
    // if (code == 103) {

    // }
    loading.close()
      // console.log(config);
    if (config.data.code == '200') {
        return config.data.data
    } else {

        return Promise.reject(config.data.message)
    }
  }, error => {
    return Promise.reject(error)
  });

  const transformParams = (data) =>{
    let params = new URLSearchParams();
    for (let item in data) {
      params.append(item, data['' + item + '']);
    }
    return params;
  }

  export function api(url,method,params) {

    let config = {
        method:method,
        url:url
    }

    if(params) {
        config.data = transformParams(params)
    } else {
        config.data = transformParams({})
    }

    return instance(config)
  }


